<template>
  <div class="home-box" v-loading.fullscreen="fullscreenLoading">
    <div class="home-header">工作时间:10:00-19:00 15分钟内发货。</div>
    <div class="home-content">
      <el-scrollbar class="service-box" height="100%" :always="true">
        <div class="home-item-box">
          <div
            :class="{ 'home-item': true, active: actItem == 'types' }"
            @click="() => (actItem = 'types')"
          >
            服务类型
          </div>
          <div
            :class="{ 'home-item': true, active: actItem == 'accounts' }"
            @click="() => (actItem = 'accounts')"
          >
            已激活的账号<span v-if="noSendOrdersNum && noSendOrdersNum > 0" class="phone-num">{{
              noSendOrdersNum
            }}</span>
          </div>
        </div>
        <template v-if="actItem == 'types'">
          <div class="title">支持的服务</div>
          <div
            :class="{ 'service-item': true, active: item.active }"
            v-for="(item, index) in types"
            :key="index"
          >
            <div class="service-item-header" @click="actTypes(item.key, index)">
              <img class="img" :src="'/images/icon' + item.accounts[0].avatar" alt="" />
              <div class="name-sum">
                <div class="name">{{ item.name }}</div>
                <!-- <div class="sum">{{ item.sum }}件</div> -->
              </div>
            </div>

            <div v-if="item.active" class="country-price-box">
              <div class="country-item" v-for="(itemCp, indexCp) in item.accounts" :key="indexCp">
                <div class="country-num-price">
                  <div class="img-country-num">
                    <!-- <img class="img" :src="'/images/icon' + itemCp.avatar" alt="" /> -->
                    <div class="country-num">
                      <!-- <div class="country">{{ itemCp.name }}</div> -->
                      <div class="num">{{ itemCp.total }}件</div>
                    </div>
                  </div>

                  <div class="price">
                    <span class="num">{{ itemCp.price }}元</span>
                  </div>
                </div>
                <div class="num-buy">
                  <el-input-number v-model="itemCp.num" :min="1" :max="10" />
                  <el-button type="success" class="buy-btn" @click.stop="orderAddFun(item, itemCp)">
                    <el-icon :size="20"> <ShoppingCart /> </el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </template>

        <template v-if="actItem == 'accounts'">
          <div class="phone-box" v-loading="phoneLoading">
            <div class="phone-item" v-for="(item, index) in orders" :key="index">
              <div class="icon-name">
                <img class="avatar" :src="'/images/icon' + item.avatar" />
                <div class="name">{{ item.name }}</div>
              </div>

              <!-- <div class="code" @click="copyText()">验证码: {{ item.code }}</div> -->

              <div class="price">{{ item.price }} x {{ item.num }} = {{ item.sum }} 元</div>

              <div class="icon">
                <div v-if="item.status == '2'" class="copytext" @click="copyText(item)">复制</div>
                <div v-if="item.status == '1'" class="delete">未发货</div>
              </div>
            </div>
          </div>
        </template>
      </el-scrollbar>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch, computed } from 'vue'
import { isMobile } from '@/utils/common'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { typeSelectTypeWithAccounts } from '@/api/interface/web/type'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAdd, orderAll } from '@/api/interface/web/order'

const router = useRouter()

if (!isMobile()) {
  router.push({ path: '/home' })
}

const fullscreenLoading = ref(false)

const userStore = useUserStore()

const actItem = ref('types')

//刷新用户信息
if (userStore.userInfo && userStore.userInfo.id) {
}

const types: any = ref([])

const getTypes = () => {
  fullscreenLoading.value = true
  typeSelectTypeWithAccounts({})
    .then((res: any) => {
      types.value = res.map((v: any) => {
        return {
          ...v,
          accounts: v.accounts.map((v2: any) => {
            return {
              ...v2,
              num: 1,
            }
          }),
          active: false,
        }
      })
    })
    .finally(() => {
      fullscreenLoading.value = false
    })
}
getTypes()

//显示隐藏折叠
const actTypes = (key: any, index: any) => {
  types.value.forEach((item: any, i: any) => {
    if (i === index) {
      item.active = !item.active
    } else {
      item.active = false
    }
  })
}

const orderAddFun = (item: any, itemCp: any) => {
  const { name } = item
  const { id, avatar, price, num } = itemCp

  if (!userStore.userInfo) {
    ElMessageBox.confirm('需要登录才能进行购买,否则去登录?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        userStore.setDialogLoginVisible(true)
      })
      .catch(() => {})
  } else {
    if (userStore.userInfo.money < parseFloat(num) * parseFloat(price)) {
      fullscreenLoading.value = false
      ElMessageBox.confirm('余额不足,是否充值?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          router.push({ path: '/pHome/score' })
        })
        .catch(() => {})
    } else {
      fullscreenLoading.value = true
      orderAdd({
        avatar,
        name,
        price,
        typeName: name,
        num,
        sum: parseFloat(price) * parseFloat(num),
        accountId: id,
      })
        .then((data: any) => {
          if (data) {
            ElMessage.success('购买成功!')
            userStore.refreshUserInfo()
            getOrdersFun()
          }
        })
        .finally(() => {
          fullscreenLoading.value = false
        })
    }
  }
}

//未发货订单
const noSendOrdersNum = computed(() => {
  return orders.value.filter((v: any) => v.status == '1').length
})

//请求号码列表
const orders: any = ref([])
const phoneLoading = ref(false)
const getOrdersFun = () => {
  if (!userStore.userInfo) {
    orders.value = []
    return
  }
  const userId = userStore.userInfo.id
  orderAll({ userId }).then((res: any) => {
    orders.value = res.map((v: any) => {
      return {
        ...v,
      }
    })
  })
}
getOrdersFun()

let intervalGetOrders: any = null
watch(
  orders,
  () => {
    const hasNeedSendOrders: any = orders.value.filter((v: any) => v.status == '1')
    if (hasNeedSendOrders.length) {
      clearIntervalFun()
      intervalGetOrders = setInterval(function () {
        getOrdersFun()
      }, 12000)
    } else {
      clearIntervalFun()
    }
  },
  {
    deep: true,
  },
)
const clearIntervalFun = () => {
  if (intervalGetOrders) {
    clearInterval(intervalGetOrders)
    intervalGetOrders = null
  }
}

onUnmounted(() => {
  clearIntervalFun()
})

watch(
  () => userStore.userInfo,
  () => {
    getOrdersFun()
  },
)

// const deletePhoneFun = () => {}

const copyText = async (item: any): Promise<void> => {
  try {
    // 使用现代的 Clipboard API
    await navigator.clipboard.writeText(item.remark)
    ElMessage.success('复制成功')
  } catch (err) {
    console.error('复制失败:', err)
    // 降级方案
    fallbackCopyText(item.remark)
  }
}

// 降级方案，用于不支持 Clipboard API 的浏览器
const fallbackCopyText = (text: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    const textarea = document.createElement('textarea')
    textarea.value = text
    textarea.style.position = 'fixed'
    textarea.style.opacity = '0'
    textarea.className = 'copyText'

    document.body.appendChild(textarea)
    textarea.focus()
    textarea.select()

    try {
      const successful = document.execCommand('copy')
      document.body.removeChild(textarea)

      if (successful) {
        ElMessage.success('复制成功')
        resolve()
      } else {
        ElMessage.error('复制失败')
        reject(new Error('复制失败'))
      }
    } catch (err) {
      document.body.removeChild(textarea)
      ElMessage.error('复制失败')
      reject(err)
    }
  })
}

onMounted(() => {
  if (userStore.userInfo) {
    userStore.refreshUserInfo()
  }
})
</script>
<style lang="scss" scoped>
.home-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .home-header {
    font-size: 2.6rem;
    border-radius: 0.8rem;
    background-color: #fff;
    border: 1px solid #e1e6ee;
    padding: 2rem 3rem;
    margin-bottom: 2rem;
    box-sizing: border-box;
  }

  .home-content {
    width: 100%;
    height: 100%;
    display: flex;
    position: relative;
    flex: 1;
    overflow-y: hidden;
    border: 1px solid #e1e6ee;
    box-sizing: border-box;
    border-radius: 0.8rem;

    .home-item-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 3rem 3rem 0 3rem;
      .home-item {
        width: 48%;
        height: 8rem;
        background-color: #f0f5ff;
        color: #75849c;
        font-size: 2.8rem;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        border-radius: 0.8rem;

        .phone-num {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 4rem;
          height: 4rem;
          font-size: 2.2rem;
          background-color: red;
          color: #fff;
          position: absolute;
          top: 0;
          right: 0;
          transform: translateX(50%) translateY(-50%);
          border-radius: 50rem;
        }
      }

      .home-item.active {
        background-color: #ea5400;
        color: #fff;
      }
    }

    .goTop {
      position: absolute;
      right: -6rem;
    }

    .service-box {
      width: 100%;

      .title {
        padding: 4rem 4rem;
        font-weight: bold;
        color: #333;
        font-size: 3.6rem;
      }

      .search-box {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 3rem;
        margin: 2rem 0 4rem 0;

        .el-input__suffix {
          font-size: 3.6rem;
        }
      }

      .service-item:last-child {
        border-bottom: 0;
      }

      .service-item {
        border-bottom: 1px solid #e1e6ee;
        width: 100%;
        // padding: 8px 0;
        box-sizing: border-box;
        min-height: 13rem;

        .service-item-header {
          display: flex;
          align-items: center;
          cursor: pointer;
          height: 13rem;
          // padding-left: 2rem;

          .img {
            width: 15rem;
            // margin-right: 2rem;
          }

          .name-sum {
            .name {
              font-size: 2.8rem;
              line-height: 3.2rem;
              font-weight: 600;
              color: #4c4c4c;
              margin-bottom: 1rem;
            }

            .sum {
              font-size: 2.4rem;
              line-height: 2.8rem;
              font-weight: 400;
              color: #979797;
            }
          }
        }

        .country-price-box {
          width: 66rem;
          min-height: 10rem;
          overflow-y: auto;
          background-color: #254d71;
          border-radius: 8px;

          .country-item:nth-child(even) {
            background-color: hsla(0, 0%, 100%, 0.1);
          }

          .country-item {
            width: 100%;
            height: 21rem;
            padding: 2rem 4.5rem;
            box-sizing: border-box;

            .country-num-price {
              display: flex;
              justify-content: space-between;
              margin-bottom: 2.4rem;

              .img-country-num {
                display: flex;

                img {
                  height: 5rem;
                }

                .country-num {
                  .country {
                    font-size: 2.8rem;
                    line-height: 3.2rem;
                    font-weight: 600;
                    color: #fff;
                    margin-bottom: 1rem;
                  }

                  .num {
                    font-size: 2.4rem;
                    line-height: 2.8rem;
                    font-weight: 400;
                    color: #fff;
                  }
                }
              }

              .price {
                display: flex;
                align-items: center;
                font-size: 2.8rem;
                color: #fff;

                .el-icon {
                  cursor: pointer;
                  font-size: 3.8rem !important;
                }

                .num {
                  width: 50px;
                  margin-left: 5px;
                  margin-right: 3px;
                  display: flex;
                  justify-content: center;
                }
              }
            }

            .num-buy {
              display: flex;
              justify-content: space-between;
              align-items: center;

              .el-input-number {
                background-color: #fff;
                border-radius: 3px;
              }

              .buy-btn {
                width: 10rem;
              }

              :deep(.el-input.is-disabled .el-input__inner) {
                -webkit-text-fill-color: #606266 !important;
              }
            }
          }
        }
      }

      .service-item.active {
        background-color: #254d71;

        .service-item-header {
          .name-sum {
            .name {
              color: #fff;
            }

            .sum {
              color: #fff;
            }
          }
        }
      }

      .more {
        width: 100%;
        padding: 4rem 0;
        display: flex;
        justify-content: center;

        .el-button {
          height: 6rem;
          width: 80%;
        }
      }

      .phone-box {
        width: 100%;
        padding: 2rem;
        box-sizing: border-box;
        .tip {
          position: absolute;
          top: 0;
          right: 0;
          font-size: 3.6rem;
          color: #ff7575;
          font-weight: bold;
          text-decoration: underline;
        }

        .title-box {
          display: flex;
          align-items: center;

          .title-item {
            font-weight: 700;
            font-size: 4rem;
            color: #333333;
            margin-bottom: 10rem;
            margin-right: 4rem;
            cursor: pointer;
          }

          .title-item.active {
            color: #ea5400;
            text-decoration: underline;
          }
        }

        .phone-item {
          border: 1px solid #e1e6ee;
          border-radius: 8px;
          display: flex;
          flex-direction: column;
          // justify-content: space-between;
          width: 100%;
          height: 24rem;
          padding: 2rem 4rem;
          padding-left: 0;
          box-sizing: border-box;
          margin-bottom: 4rem;

          .icon-name {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .avatar {
              height: 8rem;
            }

            .name {
              color: #3a5072;
              font-weight: bold;
              font-size: 2.8rem;
            }
          }

          .price {
            color: #3a5072;
            font-size: 2.6rem;
            display: flex;
            justify-content: flex-end;
            margin-bottom: 2.5rem;
          }

          .code {
            color: #3a5072;
            font-size: 2.6rem;
            cursor: pointer;
            display: flex;
            justify-content: flex-end;
            background-color: #f0f5ff;
            padding: 1rem;
            border-radius: 1rem;
          }

          .icon {
            color: #ea5400;
            font-size: 2.4rem;
            display: flex;
            justify-content: flex-end;
            .delete {
              cursor: pointer;
            }

            .copytext {
              cursor: pointer;
              color: #fff;
              padding: 0.8rem 2.5rem;
              background-color: var(--theme-color);
              border-radius: 0.5rem;
            }
          }
        }
      }
    }

    /* 滚动条滑块 */
    .country-price-box::-webkit-scrollbar-thumb {
      cursor: pointer;
      background-color: rgba(177, 182, 194, 0.3);
    }

    .country-price-box::-webkit-scrollbar-thumb:window-inactive {
      cursor: pointer;
      background-color: rgba(144, 147, 153, 0.3);
    }
  }
}
</style>
<style lang="scss">
.updateNot {
  width: 40rem;
}

.service-box {
  .el-scrollbar__bar.is-vertical {
    width: 2rem;
  }
}

.country-price-box {
  .el-scrollbar__bar.is-vertical {
    z-index: 9999999999;
    width: 2rem;
  }
}

.service-item {
  .el-scrollbar__bar {
    right: 3rem;
  }
}
</style>
